<!-- 体脂秤设备 -->
<template>
	<view class="pageview">
		<firstConnect v-if="isFirst" :device-type="deviceType" :deviceStatus="deviceStatus" @startUse="startUse"
			@retry="retry"></firstConnect>
		<template v-else>
			<view class="toptip flex align-center justify-between" v-if="!connectedDevice">
				<text>{{ blueState ? '当前设备未连接，请连接设备' : '需要开启蓝牙，连接设备' }}</text>
				<view class="btn flex align-center" @click="scanDeviceIC" v-if="blueState">
					<u-loading-icon color="#fff" :show="deviceStatus == 0 || deviceStatus == 1"></u-loading-icon>
					<text>去连接</text>
				</view>
			</view>
			<view class="startWork">
				<view v-if="isStart && isConnected">
					<weightChart ref="weightChart"></weightChart>
					<view v-if="isStart == 2">
						<view class="tip">本次测量数据已保存</view>
						<u-button shape="circle" type="primary" text="重新测量" @click="start"></u-button>
						<view class="stepbox">
							<weightStep size="lg" :bmi="wtinfo.bmi"></weightStep>
						</view>
						<view class="flex result">
							<view class="flex-sub item">
								<view>体重</view>
								<view class="u-margin-top-20">
									<text class="num">{{ weightData }}</text>
									<text class="unit">kg</text>
								</view>
							</view>
							<view class="flex-sub item">
								<view>BMI</view>
								<view class="u-margin-top-20">
									<text class="num">{{ wtinfo.bmi }}</text>
									<text class="unit">kg/m²</text>
								</view>
							</view>
							<view class="flex-sub item">
								<view>体脂率</view>
								<view class="u-margin-top-20">
									<text class="num">{{ wtinfo.bfr }}</text>
									<text class="unit">%</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<template v-else>
					<view class="imgbox">
						<image src="/static/device/F2P3.png" mode="widthFix"></image>
					</view>
					<view>
						<u-button shape="circle" :plain="!isConnected" :type="isConnected ? 'primary' : 'default'" text="开始测量"
							@click="start"></u-button>
					</view>
				</template>
			</view>
		</template>
	</view>
</template>

<script>
	var icommon = requirePlugin('ICDeviceManager');
	let ICDeviceManager = new icommon.ICDeviceManager();
	import wtdatas from '@/utils/model/data/weightdata';
	import rulerdata from '@/utils/model/data/rulerdata';
	import firstConnect from './components/firstConnect';
	import {
		mapState
	} from 'vuex';
	import {
		getAgeByBirthday
	} from '@/utils/index.js';
	let foundTimer = null;
	import weightChart from './components/weightChart';
	import weightStep from '@/components/weightStep';
	import stompMixin from '@/common/stompMixin.js';
	export default {
		mixins: [stompMixin],
		data() {
			return {
				deviceType: 'F2Pro',
				deviceTypeId: '',
				deviceStatus: 0,
				datas: '',
				weightData: 0,
				isScan: false, //是否能被扫描
				deviceName: '',
				isFirst: true,
				deviceMac: '',
				isConnected: false,
				isStart: 0,
				connectedDevice: null, // 当前连接设备
				blueState: false, //蓝牙状态
				wtinfo: {}
			};
		},
		components: {
			firstConnect,
			weightChart,
			weightStep
		},
		computed: {
			...mapState(['userInfo', 'curAccount'])
		},
		onLoad: function(optioin) {
			let that = this;
			this.deviceType = optioin.deviceType;
			if (optioin.deviceTypeId) {
				this.deviceTypeId = optioin.deviceTypeId;
				this.isFirst = true;
			} else {
				this.deviceMac = optioin.deviceMac || '';
				this.isFirst = false;
			}
			if (!that.curAccount || Object.keys(that.curAccount).length == 0) {
				return
			}
			// if (!that.curAccount.height) {
			// 	uni.showToast({
			// 		title: ''
			// 	})
			// 	return;
			// }
			// 设置蓝牙状态代理监听
			ICDeviceManager.setBleStateCallback(function(state) {
				//3 不在线 4在线
				that.blueState = state == 4;
				console.log('ble app ' + state);
			});

			// 更新用户信息
			var users = [];
			let userInfo = new icommon.ICUserInfo();
			userInfo.userIndex = 1;
			userInfo.height = that.curAccount.height;
			console.log('that.curAccount.birth', that.curAccount);
			userInfo.age = getAgeByBirthday(that.curAccount.birth);
			userInfo.weightUnit = 1;
			userInfo.weight = that.curAccount.weight;
			userInfo.weightDirection = 0;
			userInfo.sex = that.curAccount.gender == '女' ? icommon.ICConstant.ICSexType.ICSexTypeFemal : icommon.ICConstant
				.ICSexType.ICSexTypeMale;
			ICDeviceManager.updateUserInfo(userInfo);
			// 添加到用户列表
			users[users.length] = userInfo;
			// 更新用户列表
			ICDeviceManager.setUserList(users);

			// 设置连接状态和数据代理监听
			ICDeviceManager.setDelegate({
				onDeviceConnectionChanged: (device, state) => {
					// state的值意思看文档有写
					uni.setStorageSync('isConnected', state);
					if (that.deviceMac) {
						that.isConnected = state == 0;
						if (!that.isConnected) {
							that.isStart = 0;
						}
						//0 在线 1掉线
						console.log('device state=' + state, that.isConnected);
					}
				},
				onReceiveMeasureStepData: (device, step, model) => {
					console.log('step = ' + step + ', weight=' + model.weight_kg);
					console.log(model);
					console.log('that.isConnected', that.isConnected, this.isStart);
					if (!this.isStart) {
						return;
					}
					if (step == 0) {
						//console.log('weight datas:');
						wtdatas.weightImport(model);

						let text1 = '';
						let wtinfo = wtdatas['weight_info'];
						for (let wt in wtinfo) {
							text1 = text1 + wt + '：' + wtinfo[wt] + '\n';
						}
						that.datas = text1;
						that.wtinfo = wtinfo;
						that.weightData = model.weight_kg;
						that.$refs.weightChart.getServerData(that.weightData);
					} else if (step == 6) {
						wtdatas.weightImport(model);
						let text1 = '';
						let wtinfo = wtdatas['weight_info'];
						for (let wt in wtinfo) {
							text1 = text1 + wt + '：' + wtinfo[wt] + '\n';
						}
						console.log(model);
						that.datas = text1;
						that.wtinfo = wtinfo;
						that.weightData = model.weight_kg;
						that.$refs.weightChart.getServerData(that.weightData);
						that.send(
							JSON.stringify({
								detailId: that.curAccount.detailId,
								type: that.deviceType,
								data: {
									details: wtinfo,
									weightData: that.weightData
								}
							})
						);
						this.isStart = 2;
					}
				},
				onReceiveWeightData: function(device, model) {
					console.log('这个是什么状态', model);
					if (!this.isStart) {
						return;
					}
					wtdatas.weightImport(model);
					let text1 = '';
					let wtinfo = wtdatas['weight_info'];
					for (let wt in wtinfo) {
						text1 = text1 + wt + '：' + wtinfo[wt] + '\n';
					}
					that.datas = text1;
					that.weightData = model.weight_kg;
				},
				onReceiveWeightHistoryData: function(device, model) {
					console.log(model);
				},
				onReceiveSkipData: function(device, model) {
					console.log(model);
				}
			});
			// 如果插件已经初始化过就不再初始化.小程序打开后只需要初始化一次，请勿多次初始化
			if (!ICDeviceManager.isInit()) {
				ICDeviceManager.init(function(isInit) {
					// 除setBleStateCallback，updateUserInfo, setDelegate,
					// 其它接口只有初始化完以后才能调用
					// 其它接口可以在任意地方调用，无需一定要在这里面调用
					that.scanDeviceIC();
				});
			} else {
				that.scanDeviceIC();
				let isConnected = uni.getStorageSync('isConnected');
				this.isConnected = isConnected === 0;
			}
		},
		onUnload() {
			// 不在当前页面的时候断开连接
			if (this.deviceMac) {
				this.DelDevice();
			}
			this.deviceMac = '';
			this.isStart = 0;
			this.isConnected = false;
			if (foundTimer) {
				ICDeviceManager.stopScan();
				clearTimeout(foundTimer);
				foundTimer = null;
			}
		},
		methods: {
			scanDeviceIC: function() {
				let that = this;
				//10s没有找到设备，就提示没有发现设备
				foundTimer = setTimeout(() => {
					ICDeviceManager.stopScan();
					clearTimeout(foundTimer);
					foundTimer = null;
					that.deviceStatus = 3;
				}, 10000);
				// 如果设备是已知mac地址的，可以直接addDevice,无需去扫描，插件内部会自己做扫描
				ICDeviceManager.scanDevice(function(model) {
					console.log('model', model);
					if (model && model.macAddr) {
						if (!that.deviceMac) {
							// 找到设备后，停止扫描。调用scanDevice后，需开发者自己调用stopScan才会停止扫描，否则将会一直扫描，特例：蓝牙关闭后也会自己停止扫描
							ICDeviceManager.stopScan();
							that.deviceStatus = 1;
							clearTimeout(foundTimer);
							foundTimer = null;
							console.log('deviceStatus1', that.deviceStatus);
							// 添加回调成功不代表连接成功，这里只是说明设备已经添加到插 件了，连接状态看onDeviceConnectionChanged
							ICDeviceManager.addDevice(model.macAddr, function(macAddr, code) {
								that.deviceStatus = 2;
								that.deviceName = model.name;
								that.deviceMac = model.macAddr;
								that.connectedDevice = model;
								that.addDevice();
							});
						} else if (model.macAddr == that.deviceMac) {
							that.deviceName = model.name;
							// 找到设备后，停止扫描。调用scanDevice后，需开发者自己调用stopScan才会停止扫描，否则将会一直扫描，特例：蓝牙关闭后也会自己停止扫描
							ICDeviceManager.stopScan();
							clearTimeout(foundTimer);
							foundTimer = null;
							// 添加回调成功不代表连接成功，这里只是说明设备已经添加到插 件了，连接状态看onDeviceConnectionChanged
							ICDeviceManager.addDevice(that.deviceMac, function(macAddr, code) {
								console.log('add device code=' + code);
								that.connectedDevice = model;
							});
						}
					}
				});
			},
			DelDevice: function() {
				ICDeviceManager.removeDevice(this.deviceMac, function(macAddr, code) {
					console.log('remove device code=' + code);
				});
			},
			addDevice() {
				console.log('deviceTypeId', this.deviceTypeId);
				if (this.deviceTypeId) {
					this.$postAction(this.$deviceapi.addDevice, {
						bindState: 1,
						deviceTypeId: this.deviceTypeId,
						userId: this.userInfo.userId,
						devName: this.deviceName,
						mac: this.deviceMac
					});
				}
			},
			retry() {
				this.deviceStatus = 0;
				this.scanDeviceIC();
			},
			startUse() {
				this.isFirst = false;
			},
			start() {
				if (this.isConnected) {
					this.isStart = 1;
					this.$nextTick(() => {
						this.$refs.weightChart && this.$refs.weightChart.getServerData(0);
					});
				}
			}
		}
	};
</script>

<style scoped lang="scss">
	.startWork {
		width: 600upx;
		margin: 0 auto;
		padding-top: 180upx;

		.imgbox {
			width: 400upx;
			margin: 0 auto 70upx;
		}

		.tip {
			text-align: center;
			margin-bottom: 10upx;
		}

		.stepbox {
			margin-top: 50upx;
		}

		.result {
			background: #fff;
			border-radius: 16upx;
			font-size: 28upx;
			color: #a5adae;
			padding: 30upx;
			margin-top: 50upx;

			.item {
				padding: 0 16upx;
			}

			.num {
				color: #243138;
				font-size: 46upx;
				font-weight: bold;
			}

			.unit {
				color: #374547;
				font-size: 24upx;
				margin-left: 10upx;
			}
		}
	}

	.toptip {
		background: #fff;
		padding: 20upx;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;

		.btn {
			background: $u-primary;
			padding: 0 20upx;
			color: #fff;
			border-radius: 50upx;
			line-height: 60upx;
		}
	}
</style>